package com.dm.server.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dm.server.dto.Result;
import com.dm.server.dto.ScrollResult;
import com.dm.server.dto.UserDTO;
import com.dm.server.entity.*;
import com.dm.server.mapper.BlogLikeMapper;
import com.dm.server.mapper.BlogMapper;
import com.dm.server.service.BlogService;
import com.dm.server.service.FollowService;
import com.dm.server.service.UserService;
import com.dm.server.utils.RedisConstants;
import com.dm.server.utils.SystemConstants;
import com.dm.server.utils.UserHolder;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static com.dm.server.common.RedisConstants.FEED_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements BlogService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private UserService userService;
    @Resource
    private FollowService followService;
    @Resource
    private BlogLikeMapper blogLikeMapper;
    @Resource
    private BlogMapper blogMapper;


    //查看热门博客，按照点赞数量排序后，分页查看
    @Override
    public Result listHotBlogs(Integer current) {
        //分页查询
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据

        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            queryBlogUser(blog);
            isBlogLiked(blog);
        });
        //除了博客数据，还需要一些用户数据（用户名称等）
        return Result.ok(records);
    }

    //通过id查询博客具体信息，相当于你点开一条博客，前端给你id后查询数据
    @Override
    public Result getBlogById(Long id) {
        //查询到博文信息
        Blog blog = this.getById(id);
        //整合数据
        if(blog==null){
            return Result.fail("笔记不存在");
        }
        queryBlogUser(blog);
        //用户信息
        isBlogLiked(blog);
        //是否点赞过
        //返回数据
        return Result.ok(blog);
    }

    private void isBlogLiked(Blog blog) {
        UserDTO user = UserHolder.getUser();
        if(user==null){
            return;
        }
        String userId = UserHolder.getUser().getId().toString();
        String key = RedisConstants.BLOG_LIKED_KEY + blog.getId();
        //boolean isMember = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score!=null);
    }

    //点赞博客，一人一赞
    @Override
    public Result likeBlog(Long id) {

        //获取当前用户
        String userId = UserHolder.getUser().getId().toString();
        //判断用户是要点赞还是取消点赞
        String key = RedisConstants.BLOG_LIKED_KEY + id;//这个id是被点赞人的id，作为key，值value是别人给他的点赞
        boolean isLiked = stringRedisTemplate.opsForZSet().score(key, userId) != null;
        //boolean isMember = stringRedisTemplate.opsForSet().isMember(key, userId.toString());

        boolean isUpdated;
        if (!isLiked) {
            //如果还没点过赞了,数据库点赞数加一
            isUpdated = this.lambdaUpdate().setSql("liked=liked+1").eq(Blog::getId, id).update();
            //将用户id加入已点赞集合
            if (isUpdated) {
                stringRedisTemplate.opsForZSet().add(key, userId, System.currentTimeMillis());
            }
        } else {
            //如果已经点过赞了,数据库点赞数减一
            isUpdated = this.lambdaUpdate().setSql("liked=liked-1").eq(Blog::getId, id).update();
            //将用户id从已点赞集合中移除
            if (isUpdated) {
                stringRedisTemplate.opsForZSet().remove(key, userId);
            }
        }
        return isUpdated ? Result.ok() : Result.fail("服务异常");

    }
    //根据博客查询用户数据
    private void queryBlogUser(Blog blog) {//得到用户信息
        Long userId= blog.getUserId();
        User user=userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    //点赞排行榜，从redis的zset里找，如果没有就去数据库sum方法得到所有
    @Override
    public Result queryBlogLikes(Long id) {
        //查询已点赞的用户
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (CollectionUtils.isEmpty(top5)) {
            //没有点赞用户，返回空列表
            return Result.ok(Collections.emptyList());
        }
        //解析出用户id列
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        //查询出用户信息
        String idStr = StrUtil.join(",", ids);
        List<UserDTO> userDTOS = userService.query()
                .in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        //用户信息脱敏
        return Result.ok(userDTOS);
    }
    //发布博客
    @Override
    public Result saveBlog(Blog blog) {
        // 1.获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 2.保存探店笔记
        boolean isSuccess = save(blog);
        if(!isSuccess){
            return Result.fail("新增笔记失败!");
        }
        // 3.查询笔记作者的所有粉丝 select * from tb_follow where follow_user_id = ?
        List<Follow> follows = followService.query().eq("follow_user_id", user.getId()).list();
        // 4.推送笔记id给所有粉丝
        for (Follow follow : follows) {
            // 4.1.获取粉丝id
            Long userId = follow.getUserId();
            // 4.2.推送
            String key = FEED_KEY + userId;
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }
        // 5.返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
            // 1.获取当前用户
            Long userId = UserHolder.getUser().getId();
            // 2.查询收件箱 ZREVRANGEBYSCORE key Max Min LIMIT offset count
            String key = FEED_KEY + userId;
            Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                    .reverseRangeByScoreWithScores(key, 0, max, offset, 2);
            // 3.非空判断
            if (typedTuples == null || typedTuples.isEmpty()) {
                return Result.ok();
            }
            // 4.解析数据：blogId、minTime（时间戳）、offset
            List<Long> ids = new ArrayList<>(typedTuples.size());
            long minTime = 0; // 2
            int os = 1; // 2
            for (ZSetOperations.TypedTuple<String> tuple : typedTuples) { // 5 4 4 2 2
                // 4.1.获取id
                ids.add(Long.valueOf(tuple.getValue()));
                // 4.2.获取分数(时间戳）
                long time = tuple.getScore().longValue();
                if(time == minTime){
                    os++;
                }else{
                    minTime = time;
                    os = 1;
                }
            }
            os = minTime == max ? os : os + offset;
            // 5.根据id查询blog
            String idStr = StrUtil.join(",", ids);
            List<Blog> blogs = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();

            for (Blog blog : blogs) {
                // 5.1.查询blog有关的用户
                queryBlogUser(blog);
                // 5.2.查询blog是否被点赞
                isBlogLiked(blog);
            }

            // 6.封装并返回
            ScrollResult r = new ScrollResult();
            r.setList(blogs);
            r.setOffset(os);
            r.setMinTime(minTime);

            return Result.ok(r);
    }

    public Result likeBlog(Long blogId, Long userId) {
        BlogLike newLike = new BlogLike();
        newLike.setUserId(userId);
        newLike.setBlogId(blogId);
        try {
            blogLikeMapper.insert(newLike);
            // 博客表点赞数+1
            UpdateWrapper<Blog> updateWrapper = new UpdateWrapper<>();
            updateWrapper.setSql("liked = liked + 1").eq("id", blogId);
            blogMapper.update(null, updateWrapper);
            return Result.ok();
        } catch (DuplicateKeyException e) {
            return Result.fail("已点过赞");
        }
    }

}
